/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.unifor.sd.bolsa.cliente.impl;

import br.unifor.sd.bolsa.interfaces.ClienteInterface;
import br.unifor.sd.bolsa.interfaces.ListListener;
import br.unifor.sd.bolsa.util.Acao;
import br.unifor.sd.bolsa.util.Dialeto;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Pedro
 */
public class ClienteImplTCP implements ClienteInterface {

    private Socket socket;
    private Boolean ligado;
    private String dono;
    /**
     * Implementação de listener para notificar tela ao chegar uma nova mensagem.
     */
    private List<ListListener> listeners;

    public ClienteImplTCP() {
        ligado = Boolean.FALSE;
        listeners = new ArrayList<ListListener>();
    }

    public void conectar(String ip, Integer porta) throws IOException {
        socket = new Socket(ip, porta);
    }

    public void encerrarConexao() throws IOException {
        socket.close();
    }

    public void escutar() {
        InputStream input;
        byte[] bytes = new byte[1024];
        int bytesLidos = 0;
        try {
            input = this.socket.getInputStream();
            while ((bytesLidos = input.read(bytes)) != -1) {
                message(Dialeto.listaStringToList(new String(bytes, 0, bytesLidos)));
            }
        } catch (IOException ex) {
            Logger.getLogger(ClienteImplTCP.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void addListener(ListListener listener) {
        listeners.add(listener);
    }

    public void message(List<Acao> lista) {
        for (int i = 0; i < listeners.size(); i++) {
            listeners.get(i).onMessage(lista);
        }
    }

    public void iniciar() throws IOException {
        this.socket.getOutputStream().write("iniciar ".getBytes());
        this.socket.getOutputStream().flush();
    }

    public void comprarAcao(Integer acaoId) throws IOException {
        this.socket.getOutputStream().write(Dialeto.comprarToString(acaoId, this.dono).getBytes());
        this.socket.getOutputStream().flush();
    }

    public void comprarAcaoValor(Integer acaoId, Double valor) throws IOException {
        this.socket.getOutputStream().write(Dialeto.comprarComValorToString(acaoId, this.dono, valor).getBytes());
        this.socket.getOutputStream().flush();
    }

    public void venderAcao(Integer acaoId) throws IOException {
        this.socket.getOutputStream().write(Dialeto.venderToString(acaoId, this.dono).getBytes());
        this.socket.getOutputStream().flush();
    }

    /**
     * @return the dono
     */
    public String getDono() {
        return dono;
    }

    /**
     * @param dono the dono to set
     */
    public void setDono(String dono) {
        this.dono = dono;
    }
}
